<?php
// +----------------------------------------------------------------------
// | 海豚PHP框架 [ DolphinPHP ]
// +----------------------------------------------------------------------
// | 版权所有 2016~2019 广东卓锐软件有限公司 [ http://www.zrthink.com ]
// +----------------------------------------------------------------------
// | 官方网站: http://dolphinphp.com
// +----------------------------------------------------------------------

namespace app\mill\admin;

use app\admin\controller\Admin;
use app\common\builder\ZBuilder;
use app\common\model\Auth;
use app\user\model\User as UserModel;
use app\mill\model\Client as ClientModel;
use app\mill\model\Order as OrderModel;
use app\mill\model\Archives as ArchivesModel;
use app\mill\model\Audit as AuditModel;
use app\mill\model\Finance as FinanceModel;
use app\mill\model\Give as GiveModel;
use app\admin\model\Config as ConfigModel;
use app\mill\model\Log as LogModel;
use think\Db;

/**
 * 对账单控制器
 * @package app\admin\controller
 */
class Audit extends Admin
{
    public $_status = [
        -1      =>  '未通过',
        0       =>  '待审核',
        1       =>  '待对账',
        2       =>  '已对账',
    ];
    /**
     * 列表页
     * @return mixed
     * @throws \think\Exception
     * @throws \think\exception\DbException
     */
    public function index()
    {
        cookie('__forward__', $_SERVER['REQUEST_URI']);

        $id = input('id');
        // 获取查询条件
        $map = $this->getMap();
        $map[] = ['pid','=',0];
        //if(!empty($id))$map[] = ['f.id','=',$id];
        // 数据列表
        $data_list = Db::name('mill_audit')
            ->alias('f')
            ->field('f.*,o.engineering,c.company')
            ->leftJoin('mill_order o','o.order_sn=f.order_sn')
            ->leftJoin('mill_client c','c.id=o.client_id')
            ->where($map)
            ->group('f.id')
            ->order('f.rece_time desc')
            ->paginate();

        // 使用ZBuilder快速创建数据表格
        return ZBuilder::make('table')
            ->setPageTitle('对账管理（数量'.$data_list->total().'）') // 页面标题
            ->setTableName('mill_audit') // 设置表名
            ->hideCheckbox()
            ->setSearchArea([
                ['text:2', 'f.order_sn', '工程编号', 'like'],
                ['text:2', 'o.engineering', '工程名称', 'like'],
                ['text:2', 'c.company', '客户公司', 'like'],
                ['text:2', 'f.handle', '经办人', 'like'],
                //['daterange:2', 'create_time', '日期'],
            ])
            ->addColumns([ // 批量添加列
                ['order_sn', '工程编号'],
                ['engineering', '工程名称'],
                ['company', '客户公司'],
                ['note', '完成状态'],
                //['note', '备注','popover'],
                ['rece_money', '应收款项金额'],
                ['money', '实收款项金额'],
                ['rece_time', '预计收款时间','date'],
                ['handle', '经办人'],
                ['status','状态','callback',function($value, $data){
                    $status = OrderModel::status_tag($value,$this->_status[$value]);
                    if($value == -1){
                        $status .= '<br/><a href="javascript:void(0);" onclick="layer.alert(\''.$data['status_note'].'\', {title: \'审核不通过原因\'});">[查看原因]</a>';
                    }
                    return $status;
                },'__data__'],
                ['create_time', '添加日期','date'],
                ['right_button', '操作', 'btn']
            ])
            ->addTopButtons('add') // 批量添加顶部按钮
            ->addRightButton('show',['title' => '对账单预览','href' => url('show',['id' => '__id__']),'icon'=>''],['area' => ['50%', '90%'], 'title' => ['对账单预览', 'font-size:24px;text-align: center;']])
            ->addRightButton('export',['title' => '导出','href' => admin_url('show',['id'=>'__id__','print'=>2]),'class'=>'btn btn-default','icon'=>'','target'=>'_blank'])
            ->addRightButton('auditStatus',['title' => '已对账','href' => admin_url('auditStatus',['id'=>'__id__']),'class'=>'btn btn-primary ajax-get','icon'=>'','target'=>'_blank'])
            ->replaceRightButton(['status' => ['<>','1']],'',['auditStatus'])
            ->setRowList($data_list) // 设置表格数据
            ->setColumnWidth([
                'id'  => 60,
                'note'  => 100,
            ])
            ->fetch(); // 渲染模板
    }

    /**
     * 新增
     * @return mixed
     */
    public function add()
    {

        $id = input('id');

        //获取发货部的产品状态
        $role_status = GiveModel::$role[8]['status'][0];

        if ($this->request->isPost()) {
            $data = input();

            // 验证
            $result = $this->validate($data, 'audit');
            // 验证失败 输出错误信息
            if(true !== $result) $this->error($result);

            //根据发货时间来生成对账单
            if(!empty($data['address_start_time']) && empty($data['address_end_time']))$this->error('请指定发货结束时间');
            elseif(empty($data['address_start_time']) && !empty($data['address_end_time']))$this->error('请指定发货开始时间');
            elseif(empty($data['address_start_time']) && empty($data['address_end_time']))$this->error('请指定发货时间');

            $address_start_time = strtotime($data['address_start_time']);
            $address_end_time = strtotime($data['address_end_time'])+(86400-1);

            $data['address_sns'] = $this->getAddressSn($data['order_sn'],false,$address_start_time,$address_end_time);
            if(empty($data['address_sns']))$this->error('该发货时间段暂无发货单');

            $data['order_pid'] = Db::name('mill_order')->where(['order_sn'=>$data['order_sn']])->value('order_pid');
            $data['address_sns'] = implode(',',$data['address_sns']);
            $data['rece_time'] = strtotime($data['rece_time']);
            $data['create_time'] = time();
            $data['update_time'] = time();

            //判断该工程是否已计价
            $order_ids = Db::name('mill_order_archives_give')->where([['address_sn','in',$data['address_sns']]])->group('order_id')->column('order_id');
            foreach ($order_ids as $order_id){
                $is_price = Db::name('mill_order_archives_initial_price')->where(['order_id'=>$order_id])->count();
                if(empty($is_price)){
                    $order_info = Db::name('mill_order')->where(['id'=>$order_id])->find();
                    $msg = "{$order_info['order_sn']} {$order_info['engineering']} 第{$order_info['batch']}批次 未计价";
                    $this->error($msg);
                }
            }

            $re = Db::name('mill_audit')->insertGetId($data);
            if ($re) {
                //获取应收金额
                $info = AuditModel::fromData($re);
                Db::name('mill_audit')->where(['id'=>$info['id']])->update(['money'=>$info['sum_money'],'rece_money'=>$info['sum_money']]);

                $this->success('操作成功', url('index'));
            }
            $this->error('操作失败');
        }

        //获取所有工程编号
        $order_sn_list = Db::name('mill_order')->where([['give_status','=',$role_status]])->group('order_sn')->column("concat(order_sn,' ',engineering) as str_name",'order_sn');

        //JS
        $js = '<script type="text/javascript">
                $(function() {
                    
                    
                    $("#order_sn").change(function() {
                        
                        //获取订单未收款的发货单号
                        $.ajax({
                        url: \''.url("getAddressSn").'?order_sn=\'+$("#order_sn").val(),
                        type: \'GET\'
                        }).done(function(data) {
                            data = $.parseJSON(data);
                            var address_sns = data.address_sn;
                            
                            var html = "";
                            
                            $.each(address_sns,function(i,v){
                                html += "<option value=\'"+v+"\'>"+v+"</option>";
                            });
                            
                            $("#address_sns").html(html);
                            
                        });
                    
                    });
                    

                })
            </script>';

        $address_sns = [];
        $info = [];
        if(!empty($id)){
            $info = Db::name('mill_audit')->where(['id'=>$id])->find();
            if(!empty($info['address_sns'])){
                foreach (explode(',',$info['address_sns']) as $v){
                    $address_sns[$v] = $v;
                }
                $info['address_sns'] = $address_sns;
            }
            $address_sns = array_merge($this->getAddressSn($info['order_sn'],false),$address_sns);
        }
        return ZBuilder::make('form')
            ->setPageTitle('新增对账单') // 页面标题
            ->addFormItems([ // 批量添加表单项
                ['select:12||||must', 'order_sn', '选择工程编号[:请选择工程编号]', '', $order_sn_list, ''],
                //['select:||||must', 'address_sns', '选择发货单号[:请选择发货单号]', '', $address_sns, '', 'multiple'],
                //['text:||||must', 'rece_money', '应收款项金额'],
                ['date:||||must', 'address_start_time', '发货开始时间'],
                ['date:||||must', 'address_end_time', '发货结束时间'],
                ['date:||||must', 'rece_time', '预计收款时间'],
                ['text:||||must', 'handle', '经办人'],
                //['textarea:||||must', 'note', '项目数据(完成状态)'],

            ])
            ->setExtraJs($js)
            ->setFormData($info)
            ->fetch();
    }

    /**
     * 对账单浏览
     * @return mixed
     */
    public function show()
    {

        //$address_id = 1;
        //FinanceModel::audit($address_id);
        //exit;
        $id = input('id');
        $print = input('print');

        $info = [];
        if(!empty($id))$info = AuditModel::fromData($id);
        /*if(!empty($id)){
            $info = Db::name('mill_audit')
                ->alias('a')
                ->field('a.*,o.engineering,c.company,c.create_time as order_time')
                ->leftJoin('mill_order o','o.order_sn=a.order_sn')
                ->leftJoin('mill_client c','c.id=o.client_id')
                ->where(['a.id'=>$id])
                ->find();

            //获取批次
            $batch = Db::name('mill_order')->where(['order_sn'=>$info['order_sn']])->column('batch','id');
            //获取同工程下已生产的对账单
            $info['before_audit'] = Db::name('mill_audit')
                ->field('rece_time,sum(rece_money) as rece_money,sum(row_area) as row_area')
                ->where([['order_sn','=',$info['order_sn']],['pid','=',0],['id','<',$id]])
                ->find();
            //已收款金额
            $info['paid_money'] = $info['before_audit']['rece_money'];

            $new_list = [];//发货单列表
            $address_sn_span = [];//需要合并的发货单编号
            //遍历循环发货单
            $address_sns_arr = explode(',',$info['address_sns']);
            foreach ($address_sns_arr as $addsn){

                //遍历循环批次
                $list_where = [['g.address_sn','=',$addsn]];
                $order_ids = Db::name('mill_order_archives_give')->alias('g')->where($list_where)->column('DISTINCT order_id');
                foreach ($order_ids as $oid){

                    //获取发货产品信息
                    $list = Db::name('mill_order_archives_give')
                        ->alias('g')
                        ->field('a.color,a.thickness,a.model,sum(a.weld) as weld_sum,sum(a.slot) as slot_sum,sum(a.torque) as torque_sum,sum(g.id) as give_sum,a.one_area,g.address_sn,g.address_time')
                        ->leftJoin('mill_order_archives a','a.id=g.archives_id')
                        ->where($list_where)
                        ->where(['g.order_id'=>$oid])
                        ->group('a.color,a.thickness,a.model')
                        ->order('a.order_id asc')
                        ->select();

                    //循环获取各产品计价
                    if(!empty($list)){

                        $weld = 0;//焊缝
                        $slot = 0;//刨槽
                        $torque = 0;//开孔
                        foreach ($list as &$v){

                            $price_where = [
                                ['order_id','=',$oid],
                                ['color','=',$v['color']],
                                ['thickness','=',$v['thickness']],
                                ['model','=',$v['model']],
                            ];
                            $price_info = Db::name('mill_order_archives_initial_price')->where($price_where)->find();
                            $v = array_merge($v,$price_info);

                            $v['unit'] = 'm²';
                            $v['batch'] = $batch[$v['order_id']];
                            $v['row_area'] = ceil(($v['one_area'] * $v['give_sum'])*10000)/10000;

                            if(empty($address_sn_span[$addsn]))$address_sn_span[$addsn] = 1;
                            else $address_sn_span[$addsn] ++;

                            $weld += $v['weld_sum'];
                            $slot += $v['slot_sum'];
                            $torque += $v['torque_sum'];
                        }

                        //类型 1:焊缝 2: 刨槽 3:开孔
                        $tgd_type_arr = [
                            //合计焊缝
                            ['field'=>'weld','title'=>'焊缝长度','type'=>1,'value'=>$weld],
                            //合计开槽
                            ['field'=>'slot','title'=>'刨槽长度','type'=>2,'value'=>$slot],
                            //矩管长度
                            ['field'=>'torque','title'=>'开孔个数','type'=>3,'value'=>$torque],
                        ];
                        foreach ($tgd_type_arr as $tp){
                            if(!empty($tp['value'])){
                                $tp_info = Db::name('mill_order_archives_initial_price')->where(['order_id'=>$oid,'type'=>$tp['type']])->find();
                                if($tp_info['price'] > 0){

                                    $tp_info['unit'] = 'm';
                                    $tp_info['give_sum'] = '';
                                    $tp_info['row_area'] = $tp['value'];
                                    $tp_info['model'] = $tp['title'];
                                    $tp_info['basic_price'] = $tp_info['price'];

                                    $list[] = array_merge($list[0],$tp_info);
                                    $address_sn_span[$addsn] ++;
                                }
                            }
                        }

                        //配件
                        if(empty($info['before_audit']['rece_time'])){
                            $extra = Db::name('mill_order_archives_extra')
                                ->alias('e')
                                ->field('e.model_sn,e.number,p.*')
                                ->leftJoin('mill_order_archives_initial_price p','p.model_sn=e.model_sn')
                                ->where([['e.order_id','=',$oid],['p.price','>',0]])
                                ->select();
                            if(!empty($extra)){
                                foreach ($extra as $e){
                                    $e_info = $list[0];
                                    $e_info['unit'] = '';
                                    $e_info['color'] = '';
                                    $e_info['thickness'] = '';
                                    $e_info['give_sum'] = $e['number'];
                                    $e_info['row_area'] = '';
                                    $e_info['model'] = $e['model_sn'];
                                    $e_info['basic_price'] = $e_info['price'];

                                    $list[] = $e_info;
                                    $address_sn_span[$addsn] ++;
                                }
                            }

                        }

                    }
                    $new_list = array_merge($new_list,$list);
                }

            }


            $info['list'] = $new_list;
            $info['address_sn_span'] = $address_sn_span;


        }*/

        $html = AuditModel::toHtml($info,$print);

        if(empty($print))$html = str_replace('window.print();',"",$html);

        exit($html);

        $table_arr = AuditModel::fromTabale($info);
        $table_head = $table_arr['head'];
        $table_data = $table_arr['data'];

        return ZBuilder::make('form')
            ->setPageTitle('对账单详情') // 页面标题
            ->addFormItems([ // 批量添加表单项
                ['complexTable:12', 'audit', '', $table_data, $table_head],
            ])
            ->setFormData($info)
            ->fetch();
    }
    /**
     * 对账单浏览
     * @return mixed
     */
    public function show2()
    {
        return $this->show();
    }

    /**
     * 获取订单未收款的发货单号
     * @param null $order_sn
     * @return mixed
     */
    public function getAddressSn($order_sn=null,$json = true,$start_time = 0,$end_time = 0)
    {
        if(empty($order_sn))$order_sn = input('order_sn');

        $order_pid = Db::name('mill_order')->where(['order_sn'=>$order_sn])->value('order_pid');
        $where = [];
        $where[] = ['order_pid','=',$order_pid];
        $where[] = ['address_sn','>=',1];
        if(!empty($start_time) && empty($end_time))$where[] = ['address_time','>=',$start_time];
        elseif(empty($start_time) && !empty($end_time))$where[] = ['address_time','<=',$end_time];
        elseif(!empty($start_time) && !empty($end_time))$where[] = ['address_time','between',"{$start_time},{$end_time}"];

        $address_sn_sub = Db::name('mill_audit')
            ->where(['order_sn'=>$order_sn])
            ->column('address_sns');
        $address_sn_sub = implode(',',$address_sn_sub);
        if(!empty($address_sn_sub))$where[] = ['address_sn','not in',$address_sn_sub];

        $address_sn = Db::name('mill_order_archives_give')
            ->where($where)
            ->group('address_sn')
            ->order('address_sn asc')
            ->column('address_sn as address_sn1','address_sn');

        if($json)exit(json_encode(['address_sn'=>$address_sn]));
        return $address_sn;

    }

    /**
     * 待审核对账列表页
     * @return mixed
     */
    public function examine()
    {
        cookie('__forward__', $_SERVER['REQUEST_URI']);

        // 获取查询条件
        $map = $map0 = $map01 = $this->getMap();
        // 数据列表
        $data_list = Db::name('mill_audit')
            ->alias('f')
            ->field('f.*,o.engineering,c.company')
            ->leftJoin('mill_order o','o.order_sn=f.order_sn')
            ->leftJoin('mill_client c','c.id=o.client_id')
            ->where([['f.status','=','0'],['f.pid','=',0]])
            ->where($map)
            ->group('f.id')
            ->order('f.id desc')
            ->paginate();
        //待审核
        $map0[] = ['status','eq','0'];
        $total0 = Db::name('mill_audit')->where($map0)->count();
        //未通过
        $map01[] = ['status','eq','-1'];
        $total01 = Db::name('mill_audit')->where($map01)->count();

        // 使用ZBuilder快速创建数据表格
        return ZBuilder::make('table')
            ->setPageTitle('对账单审核（待审核'.$total0.'/未通过'.$total01.'）') // 页面标题
            ->setTableName('mill_audit') // 设置表名
            ->hideCheckbox()
            ->setSearchArea([
                ['text:2', 'f.order_sn', '工程编号', 'like'],
                ['text:2', 'o.engineering', '工程名称', 'like'],
                ['text:2', 'c.company', '客户公司', 'like'],
                ['text:2', 'f.handle', '经办人', 'like'],
                //['daterange:2', 'create_time', '日期'],
            ])
            ->addColumns([ // 批量添加列
                ['order_sn', '工程编号'],
                ['engineering', '工程名称'],
                ['company', '客户公司'],
                ['note', '完成状态'],
                //['note', '备注','popover'],
                ['rece_money', '应收款项金额'],
                ['rece_time', '预计收款时间','date'],
                ['handle', '经办人'],
                ['status','状态','callback',function($value, $data){
                    $status = OrderModel::status_tag($value,$this->_status[$value]);
                    if($value == -1){
                        $status .= '<br/><a href="javascript:void(0);" onclick="layer.alert(\''.$data['status_note'].'\', {title: \'审核不通过原因\'});">[查看原因]</a>';
                    }
                    return $status;
                },'__data__'],
                ['create_time', '添加日期','date'],
                ['right_button', '操作', 'btn']
            ])
            ->addRightButton('show2',['title' => '对账单预览','href' => url('show',['id' => '__id__']),'icon'=>''],['area' => ['50%', '90%'], 'title' => ['对账单预览', 'font-size:24px;text-align: center;']])
            ->addRightButton('backEnable',['title' => '审核通过','href' => url('backEnable',['id' => '__id__'])."?fieldv=status|1",'class'=>'btn btn-default ajax-get','icon'=>''])
            ->addRightButton('notDisable',['title' => '审核不通过','href' => url('notDisable',['id' => '__id__','field'=>'status']),'icon'=>''],['area' => ['780px', '50%'], 'title' => ['审核不通过原因', 'font-size:24px;text-align: center;']])
            ->replaceRightButton(['status' => ['in', '1']], '', 'backEnable,notDisable')
            ->setRowList($data_list) // 设置表格数据
            ->fetch(); // 渲染模板

    }
    /**
     * 已对账
     */
    public function auditStatus()
    {

        $id = input('param.id');

        $info = Db::name('mill_audit')->where('id', $id)->find();

        if (false === Db::name('mill_audit')->where('id', $id)->update(['status'=>2])) $this->error('操作失败');
        //对账人和对账时间
        Db::name('mill_audit')->where('id', $id)->update(['audit_uid'=>UID,'audit_time'=>time()]);

        //推送消息
        $status_str = '已对账';
        $content = "工程编号<span class='text-primary'>[{$info['order_sn']}]</span>{$status_str}";
        $href = admin_url('index')."?_s=f.id={$info['id']}&_o=f.id=eq";;
        //LogModel::send_message("对账单{$status_str}",$content,$href);

        $this->success('提交成功', null, '_parent_reload');
    }
    /**
     * 审核
     */
    public function backEnable()
    {

        $id = input('param.id');
        $fieldv = input('param.fieldv');
        $fieldv = explode('|',$fieldv);

        $info = Db::name('mill_audit')->where('id', $id)->find();

        if (false === Db::name('mill_audit')->where('id', $id)->update([$fieldv[0]=>$fieldv[1]])) {
            $this->error('审核失败，工程ID：'.$id);
        }
        //审核人员
        Db::name('mill_audit')->where('id', $id)->update([$fieldv[0].'_verify_uid'=>UID]);
        //审核时间
        Db::name('mill_audit')->where('id', $id)->update([$fieldv[0].'_time'=>time()]);

        //推送消息
        $status_str = '审核';
        $content = "工程编号<span class='text-primary'>[{$info['order_sn']}]</span>{$status_str}通过";
        $href = admin_url('index')."?_s=f.id={$info['id']}&_o=f.id=eq";;
        //LogModel::send_message("对账单{$status_str}",$content,$href);

        $this->success('提交成功', null, '_parent_reload');
    }
    /**
     * 审核不通过
     */
    public function notDisable()
    {
        $field = input('param.field');
        if ($this->request->isPost()) {
            $data = input();
            $id = input('param.id');
            if (false === Db::name('mill_audit')->where('id', $id)->update([$field=>-1])) {
                $this->error('审核失败，工程ID：'.$id);
            }
            if(!empty($data[$field.'_note']))Db::name('mill_audit')->where('id', $id)->update([$field.'_note'=>$data[$field.'_note']]);
            //审核人员
            Db::name('mill_audit')->where('id', $id)->update([$field.'_verify_uid'=>UID]);
            //审核时间
            Db::name('mill_audit')->where('id', $id)->update([$field.'_time'=>time()]);

            $this->success('操作成功', null, '_parent_reload');
        }

        return ZBuilder::make('form')
            ->setPageTitle('审核不通过原因') // 页面标题
            ->addFormItem('hidden', 'id')
            ->addFormItems([ // 批量添加表单项
                ['textarea', $field.'_note', '[:请输入审核不通过原因]'],
            ])
            ->layout([$field.'_note'=>12])
            ->fetch();
    }

    /**
     * 收款记录
     * @return mixed
     * @throws \think\Exception
     * @throws \think\exception\DbException
     */
    public function logList()
    {
        cookie('__forward__', $_SERVER['REQUEST_URI']);

        // 获取查询条件
        $pid = input('pid');
        $map = $this->getMap();
        $map[] = ['pid','=',$pid];
        $map[] = ['pid','>',0];

        // 数据列表
        $data_list = Db::name('mill_audit')
            ->alias('f')
            ->field('f.*,o.engineering,c.company')
            ->leftJoin('mill_order o','o.order_sn=f.order_sn')
            ->leftJoin('mill_client c','c.id=o.client_id')
            ->where($map)
            ->group('f.id')
            ->order('f.id desc')
            ->paginate()
            ->each(function ($v){
                $v['money_str'] = FinanceModel::getMoneyStr($v['type'],$v['money'],true);
                $v['money'] = FinanceModel::getMoneyStr($v['type'],$v['money']);

                return $v;
            })
        ;

        // 使用ZBuilder快速创建数据表格
        return ZBuilder::make('table')
            ->setPageTitle('收款记录（数量'.$data_list->total().'）') // 页面标题
            ->setTableName('mill_audit') // 设置表名
            ->hideCheckbox()
            ->setSearchArea([
                //['text:2', 'f.order_sn', '工程编号', 'like'],
                //['text:2', 'o.engineering', '工程名称', 'like'],
                //['text:2', 'c.company', '客户公司', 'like'],
                //['text:2', 'f.handle', '经办人', 'like'],
                //['daterange:2', 'create_time', '日期'],
            ])
            ->addColumns([ // 批量添加列
                ['order_sn', '工程号'],
                ['engineering', '工程名称'],
                ['company', '客户公司'],
                ['money_str','收款金额(元)'],
                ['note', '收款说明'],
                ['handle', '经办人'],
                /*['status','状态','callback',function($value, $data){
                    $status = OrderModel::status_tag($value,$this->_status[$value]);
                    if($value == -1){
                        $status .= '<br/><a href="javascript:void(0);" onclick="layer.alert(\''.$data['status_note'].'\', {title: \'审核不通过原因\'});">[查看原因]</a>';
                    }
                    return $status;
                },'__data__'],*/
                ['create_time', '添加日期','date'],
                ['right_button', '操作', 'btn']
            ])
            ->addTopButton('logAdd',['title' => '新增','href' => url('logAdd',['pid'=>$pid]),'icon'=>'','class'=>'btn btn-primary disable-dch'],['area' => ['1500px', '70%'], 'title' => ['新增', 'font-size:24px;text-align: center;']])
            ->addRightButton('logEdit',['title' => '编辑','href' => url('logAdd',['id'=>'__id__']),'icon'=>'','class'=>'btn btn-primary disable-dch'],['area' => ['1500px', '70%'], 'title' => ['编辑', 'font-size:24px;text-align: center;']])
            ->setRowList($data_list) // 设置表格数据
            ->setColumnWidth([
                'id'  => 60,
                'note'  => 100,
            ])
            ->fetch(); // 渲染模板
    }
    /**
     * 新增
     * @return mixed
     */
    public function logAdd()
    {
        $id = input('id');
        $pid = input('pid');

        if ($this->request->isPost()) {
            $data = input();

            // 验证
            $rule = [
                'pid|标题' => 'require',
                //'type|收入类型' => 'require',
                'money|调账收入' => 'require',
                'handle|经办人' => 'require',
                'note|调账说明' => 'require',
            ];
            $result = $this->validate($data, $rule);
            // 验证失败 输出错误信息
            if(true !== $result) $this->error($result);

            $data['update_time'] = time();

            if($id)$re = Db::name('mill_audit')->where(['id'=>$id])->update($data);
            else{
                $data['create_time'] = time();
                $re = Db::name('mill_audit')->insert($data);
            }

            if ($re) $this->success('操作成功','','_parent_reload');
            $this->error('操作失败');
        }

        if($id){
            $info = Db::name('mill_audit')
                ->alias('f')
                ->field('f.*,o.order_sn,o.engineering')
                ->leftJoin('mill_order o','o.order_sn=f.order_sn')
                ->where(['f.id'=>$id])
                ->find();
        }
        else{
            $finance = Db::name('mill_audit')
                ->alias('f')
                ->field('f.*,o.order_sn,o.engineering')
                ->leftJoin('mill_order o','o.order_sn=f.order_sn')
                ->where(['f.id'=>$pid])
                ->find();

            $info = [
                'pid'           =>  $pid,
                'order_sn'      =>  $finance['order_sn'],
                'engineering'   =>  $finance['engineering'],
            ];
        }

        return ZBuilder::make('form')
            ->setPageTitle('新增收款记录') // 页面标题
            ->addStatic('order_sn','工程号')
            ->addStatic('engineering','工程名称')
            ->addFormItems([ // 批量添加表单项
                ['hidden','pid'],
                ['hidden','order_sn'],
                //['radio:||||must','type', '收入类型','',['调减收入','调增收入'],1],
                ['text:||||must', 'money', '收款金额'],
                ['text:||||must', 'handle', '经办人'],
                ['textarea:||||must', 'note', '收款说明'],

            ])
            ->setFormData($info)
            ->fetch();
    }
    /**
     * 收款记录
     * @return mixed
     * @throws \think\Exception
     * @throws \think\exception\DbException
     */
    public function invoiceList()
    {
        cookie('__forward__', $_SERVER['REQUEST_URI']);

        // 获取查询条件
        $audit_id = input('audit_id');
        $map = $this->getMap();
        $map[] = ['audit_id','=',$audit_id];

        // 数据列表
        $data_list = Db::name('mill_audit_invoice')
            ->alias('f')
            ->field('f.*,o.engineering,c.company')
            ->leftJoin('mill_order o','o.order_sn=f.order_sn')
            ->leftJoin('mill_client c','c.id=o.client_id')
            ->where($map)
            ->group('f.id')
            ->order('f.id desc')
            ->paginate()
            ->each(function ($v){
                $v['money_str'] = FinanceModel::getMoneyStr($v['type'],$v['money'],true);
                $v['money'] = FinanceModel::getMoneyStr($v['type'],$v['money']);

                return $v;
            })
        ;

        // 使用ZBuilder快速创建数据表格
        return ZBuilder::make('table')
            ->setPageTitle('开票记录（数量'.$data_list->total().'）') // 页面标题
            ->setTableName('mill_audit_invoice') // 设置表名
            ->hideCheckbox()
            ->setSearchArea([
                //['text:2', 'f.order_sn', '工程编号', 'like'],
                //['text:2', 'o.engineering', '工程名称', 'like'],
                //['text:2', 'c.company', '客户公司', 'like'],
                //['text:2', 'f.handle', '经办人', 'like'],
                //['daterange:2', 'create_time', '日期'],
            ])
            ->addColumns([ // 批量添加列
                ['order_sn', '工程号'],
                ['engineering', '工程名称'],
                ['company', '客户公司'],
                ['money_str','开票金额(元)'],
                ['note', '开票说明'],
                ['handle', '经办人'],
                /*['status','状态','callback',function($value, $data){
                    $status = OrderModel::status_tag($value,$this->_status[$value]);
                    if($value == -1){
                        $status .= '<br/><a href="javascript:void(0);" onclick="layer.alert(\''.$data['status_note'].'\', {title: \'审核不通过原因\'});">[查看原因]</a>';
                    }
                    return $status;
                },'__data__'],*/
                ['create_time', '添加日期','date'],
                ['right_button', '操作', 'btn']
            ])
            ->addTopButton('invoiceAdd',['title' => '新增','href' => url('invoiceAdd',['audit_id'=>$audit_id]),'icon'=>'','class'=>'btn btn-primary disable-dch'],['area' => ['1500px', '70%'], 'title' => ['新增', 'font-size:24px;text-align: center;']])
            ->addRightButton('invoiceEdit',['title' => '编辑','href' => url('invoiceAdd',['id'=>'__id__']),'icon'=>'','class'=>'btn btn-primary disable-dch'],['area' => ['1500px', '70%'], 'title' => ['编辑', 'font-size:24px;text-align: center;']])
            ->setRowList($data_list) // 设置表格数据
            ->setColumnWidth([
                'id'  => 60,
                'note'  => 100,
            ])
            ->fetch(); // 渲染模板
    }
    /**
     * 新增
     * @return mixed
     */
    public function invoiceAdd()
    {
        $id = input('id');
        $audit_id = input('audit_id');

        if ($this->request->isPost()) {
            $data = input();

            // 验证
            $rule = [
                //'type|收入类型' => 'require',
                'money|调账收入' => 'require',
                'handle|经办人' => 'require',
                'note|调账说明' => 'require',
            ];
            $result = $this->validate($data, $rule);
            // 验证失败 输出错误信息
            if(true !== $result) $this->error($result);

            $data['update_time'] = time();

            if($id)$re = Db::name('mill_audit_invoice')->where(['id'=>$id])->update($data);
            else{
                $data['create_time'] = time();
                $re = Db::name('mill_audit_invoice')->insert($data);
            }

            if ($re) $this->success('操作成功','','_parent_reload');
            $this->error('操作失败');
        }

        if($id){
            $info = Db::name('mill_audit_invoice')
                ->alias('f')
                ->field('f.*,o.order_sn,o.engineering')
                ->leftJoin('mill_order o','o.order_sn=f.order_sn')
                ->where(['f.id'=>$id])
                ->find();
        }
        else{
            $finance = Db::name('mill_audit')
                ->alias('f')
                ->field('f.*,o.order_sn,o.engineering')
                ->leftJoin('mill_order o','o.order_sn=f.order_sn')
                ->where(['f.id'=>$audit_id])
                ->find();

            $info = [
                'audit_id'      =>  $audit_id,
                'order_sn'      =>  $finance['order_sn'],
                'engineering'   =>  $finance['engineering'],
            ];
        }

        return ZBuilder::make('form')
            ->setPageTitle('新增开票记录') // 页面标题
            ->addStatic('order_sn','工程号')
            ->addStatic('engineering','工程名称')
            ->addFormItems([ // 批量添加表单项
                ['hidden','pid'],
                ['hidden','order_sn'],
                //['radio:||||must','type', '收入类型','',['调减收入','调增收入'],1],
                ['text:||||must', 'money', '开票金额'],
                ['text:||||must', 'handle', '经办人'],
                ['textarea:||||must', 'note', '开票说明'],

            ])
            ->setFormData($info)
            ->fetch();
    }


}
